/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package WebServices;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import smartgrid.Contract;
import smartgrid.Contracts;
import smartgrid.DataLine;

/**
 *
 * @author andre
 */
@WebService(serviceName = "MeteringService")
public class MeteringService {

    /**
     * Web service operation
     */
    @WebMethod(operationName = "getContracts")
    public java.util.List<String> getContracts(@WebParam(name = "nContract")
    int nContract) {
        System.out.println("webservice");
        ArrayList<String> res = new ArrayList<String>();
        Iterator<Contract> it = Arrays.asList(Contract.listContractByQuery(null, null)).iterator(); 
        while(nContract > 0 && it.hasNext()){
            res.add(it.next().getNumber());
            nContract--;
        }
        
        return res;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "addDataLine")
    public Boolean addDataLine(@WebParam(name = "contract")
    String contract, @WebParam(name = "value")
    float value, @WebParam(name = "timestamp")
    Date timestamp, @WebParam(name = "hora")
    short hora, @WebParam(name = "min")
    short min, @WebParam(name = "unit")
    String unit) {
        try {
            InitialContext initCtx = new InitialContext();        
            Contracts cm = (Contracts)initCtx.lookup("java:global/SmartGridEA/ContractsManager");
            
            Contract c = cm.getContractByNumber(contract);
            
            if(c == null) return false;
            
            DataLine d = DataLine.createDataLine();
            d.setTimeStamp(timestamp);
            d.setContract(c);
            d.setHora(hora);
            d.setMinuto(min);
            d.setTariff(c.getTariff_CurrentTarif_role());
            d.setUnit(unit);
            d.setValue(value);
            return d.save();
        } catch (NamingException ex) {
            Logger.getLogger(MeteringService.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        
    }
}
